<?php declare(strict_types=1);

namespace app\admin\service;

use app\common\helper\ConstBase;
use app\common\model\CasesCategory;
use app\common\model\Cases;
use think\facade\Log;

class CasesService
{
    /**
     * 列表
     * @return void
     */
    public function getCasesList($keywords, $categoryId, $pageSize)
    {
        $model = new Cases();
        return $model
            ->where(function ($query) use ($keywords, $categoryId, $pageSize) {
                if($keywords){
                    $query->where('name|keywords', 'like', $keywords .'%');
                }
                if($categoryId){
                    $query->where('category_id', $categoryId);
                }
            })
            ->order(['sort'=>'desc','id'=>'desc'])
            ->paginate($pageSize)
            ->each(function($item) {
                $item['category_name'] = $this->getCategoryName($item->category_id);
                $item['tag_name'] = (new TagService())->getTagName($item->tag_ids);
                $item['dev_type_name'] = $item->dev_type ? ConstBase::GetDevTypeName($item->dev_type) : '';
                return $item;
            });
    }

    /**
     * 更新数据
     * @param $data
     * @return void
     */
    public function updateOrInsert($data)
    {
        try {
            $model = new Cases();
            if (isset($data['id'])) {
                $item = $model->find($data['id']);
                $item->save($data);
            } else {
                $model->save($data);
            }
            return json(['code'=>0, 'msg'=>'编辑成功']);
        } catch (\Exception $e) {
            Log::error("edit cases error:". $e->getMessage());
            return json(['code'=>1, 'msg'=>'编辑失败，'. $e->getMessage()]);
        }
    }

    /**
     * 操作
     * @return void
     */
    public function action($id, $type){
        $model = new Cases();
        try {
            $status = $type ? 1:0;
            $model->where('id', $id)->update(['status'=>$status, 'update_time'=>time()]);

            return json(['code'=>0, 'msg'=>'操作成功']);
        } catch (\Exception $e) {
            Log::error("action cases {$id} error:". $e->getMessage());

            return json(['code'=>1, 'msg'=>'操作失败，'. $e->getMessage()]);
        }
    }

    /**
     * 删除记录
     * @param $id
     * @return void
     */
    public function delete($id)
    {
        try {
            $ids = !is_array($id) ? [$id]:$id;
            $model = new Cases();
            $model::destroy($id);

            return json(['code'=>0, 'msg'=>'删除成功']);
        } catch (\Exception $e) {
            Log::error("delete cases " .json_encode($ids). " failed：".$e->getMessage());

            return json(['code'=>1, 'msg'=>'删除失败']);
        }
    }

    /**
     * 查询一条记录
     * @param $id
     * @return Article|array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOne($id)
    {
        $model = new Cases();
        return $model->find($id);
    }

    /**
     * 分类列表
     * @return void
     */
    public function getCasesCategoryList($pageSize = MAX_SIZE)
    {
        $model = new CasesCategory();
        return $model
            ->field('id, name, sort, status, update_time')
            ->order(['sort' => 'desc', 'id' => 'desc'])
            ->paginate($pageSize);
    }

    /**
     * 编辑分类
     * @param $data
     * @return \think\response\Json
     */
    public function categoryUpdateOrInsert($data)
    {
        try {
            $model = new CasesCategory();
            if (isset($data['id'])) {
                $item = $model->find($data['id']);
                $item->save($data);
            } else {
                $model->save($data);
            }
            return json(['code'=>0, 'msg'=>'编辑成功']);
        } catch (\Exception $e) {
            Log::error("edit cases category error:". $e->getMessage());
            return json(['code'=>1, 'msg'=>'编辑失败，'. $e->getMessage()]);
        }
    }

    /**
     * 删除分类
     * @param $id
     * @return void
     */
    public function categoryDelete($id)
    {
        $item = (new Cases())->where(['status'=>1, 'category_id'=>$id])->find();
        if($item){
            return json(['code'=>1, 'msg'=>'请先删除该分类下的文章']);
        }
        try {
            $ids = !is_array($id) ? [$id]:$id;
            $model = new CasesCategory();
            $model::destroy($id);

            return json(['code'=>0, 'msg'=>'删除成功']);
        } catch (\Exception $e) {
            Log::error("delete cases category " .json_encode($ids). " failed：".$e->getMessage());

            return json(['code'=>1, 'msg'=>'删除失败']);
        }
    }

    /**
     * 获取分类
     * @param $categoryId
     * @return void
     */
    public function getCategoryBy($categoryId)
    {
        $model = new CasesCategory();
        return $model->where('id', $categoryId)->find();
    }

    /**
     * 获取分类名称
     * @param $categoryId
     * @return void
     */
    public function getCategoryName($categoryId)
    {
        $model = new CasesCategory();
        return $model->where('id', $categoryId)->value('name');
    }
}